import {Component, OnInit, AfterViewInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {ElementRef} from '@angular/core';

import {AuthService} from '../../../auth/auth.service';

import {UserVo} from '../../../entity/vo/user.vo';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthService]
})
export class LoginComponent implements OnInit, AfterViewInit {

  validateForm: FormGroup;
  isLoginBtnLoading = false;
  loginSuccessTip = false;
  loginSuccessText = '';
  loginErrorTip = false;
  loginErrorText = '';

  constructor(private fb: FormBuilder,
              private router: Router,
              private ef: ElementRef,
              private authService: AuthService) {
  }

  ngOnInit() {
    window.addEventListener('resize', () => {
      this.windowResize();
    });
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [true]
    });
  }

  ngAfterViewInit() {
    this.windowResize();
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      this.isLoginBtnLoading = true;
      this.loginSuccessTip = false;
      this.loginErrorTip = false;
      const user = new UserVo();
      user.username = this.validateForm.controls['username'].value;
      user.password = this.validateForm.controls['password'].value;
      this.authService.login(user).then(res => {
        switch (res.retcode) {
          case 1:
            this.loginSuccessText = res.msg;
            this.loginSuccessTip = true;
            this.router.navigateByUrl('home');
            break;
          case -1:
            this.isLoginBtnLoading = false;
            this.loginErrorText = res.msg;
            this.loginErrorTip = true;
            break;
        }
      }).catch(err => {
        console.error(err);
        this.isLoginBtnLoading = false;
      });
    }
  }

  inputChange(): void {
    this.loginSuccessTip = false;
    this.loginErrorTip = false;
  }

  windowResize(): void {
    // 直接操作DOM以防止脏检查
    const containerDom = this.ef.nativeElement.querySelector('.login-form');
    containerDom.style.marginTop = `-${containerDom.offsetHeight / 2}px`;
  }

}
